import React, { useState, createContext, useEffect } from 'react'
import reactLogo from './assets/react.svg'
import { useLocalStorage, useWindosScroll } from './hooks'
import viteLogo from '/vite.svg'
import './App.css'
import {useRef} from 'react'

// 1.create Context Object
const { Provider, Consumer } = createContext()

// 3. custome data
function ComC() {
  return (
    <Consumer>
      {(value) => (
        <>
          <div>我是C组件</div>
          <div>{value}</div>
        </>
      )}
    </Consumer>
  )
}

function ComA() {
  return (
    <>
      <div>我是A组件</div>
      <ComC></ComC>
    </>
  )
}

function Counter(props) {
  const [count, setCount] = useState(() => {
    return props.count
  })

  return (
    <button
      onClick={() => {
        setCount(count + 1)
      }}
    >
      Counter {count}
    </button>
  )
}

function App() {
  const [msg, setMsg] = useState('我来自App组件')
  const [count, setCount] = useState(0)
  const [y] = useWindosScroll()
  const [message, setMessage] = useLocalStorage('key_message', '')
  const [channels, setChannels] = useState([])
  const divRef = useRef(null)

  const changeMsg = (value) => {
    console.log('子组件传过来的值', value)
    setMsg(value)
  }

  useEffect(() => {
    document.title = `当前点击了${count}次`
    console.log('副作用函数执行了', y)
    console.log('divRef', divRef, divRef.current.textContent);
    setMessage('count ' + count)
    setMsg(count)

    // 组件卸载是自动执行
    // 组件更新时，下一个useEffect执行前，执行
    return () => {}
  }, [count])

  useEffect(() => {
    const getData = async () => {
      try {
        const res = await fetch('http://geek.itheima.net/v1_0/channels').then(
          (resp) => resp.json()
        )
        console.log(res)
        setChannels(res.data.channels)
      } catch (error) {
        console.error(error)
      }
    }

    getData()
  }, [])

  // 2. Provide data
  return (
    <Provider value={msg}>
      <div>
        <ComA></ComA>
        <Counter count={10}></Counter>
        <Counter count={20}></Counter>
        <button
          onClick={() => {
            setCount(count + 1)
          }}
        >
          count {count} increades
        </button>
        <hr />
        <div ref={divRef}>获取ref {count}</div>
        <hr />
        <div className="tab-w">
          {channels.map((item, index) => {
            return (
              <React.Fragment key={item.id}>

                <div className="tab" key={item.id}>
                  {item.name}
                </div>
              </React.Fragment>
            )
          })}
        </div>
      </div>
    </Provider>
  )
}

export default App
